package com.xiaochun.hxhj;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.myview.CustomProgressDialog;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.util.ExitAppUtil;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class BuyBookActivity extends BaseActivity {


    private String id;
    private String price;
    private TextView tv_price;
    private TextView tv_buy;
    private CustomProgressDialog customProgressDialog;
    private String order_sn;
    private JSONObject paydata;
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();
    }

    @Override
    protected void initListener() {
        tv_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String token = getUserInfo("token");
                if ("".equals(token) || token == null){
                    Intent intent = new Intent(context,LoginActivity.class);
                    startActivity(intent);
                }else{
                    getOrderid();
                }
            }
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_buy_book;
    }

    @Override
    protected void initView() {
//        EventBus.getDefault().register(this);
        changeTitle("收费书籍购买");
//        saveNoticeList("name","王冰寒");
        id = getIntent().getStringExtra("id");
        tv_price = findViewById(R.id.tv_price);
        tv_buy = findViewById(R.id.tv_buy);
        getData();
    }


    @Override
    protected void initData() {

    }
    private void getData() {
        String token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/speed/speed_info";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("id", id);
//        paramsMap.put("token", token);
        MyLog.e("购买会员", id + "   ");
//        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handlerData.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");

                    price = data.getString("price");
                    msg.arg1 = 2;
                    handlerData.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handlerData.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handlerData.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handlerData.sendMessage(msg);
                }
            }
        });
    }
    private void getOrderid() {
        String token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/speed/buy_member";
        HashMap<String, String> paramsMap = new HashMap<>();
//        paramsMap.put("id", id);
        paramsMap.put("token", token);
        MyLog.e("获取订单号", token + "   ");
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handlerData.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    order_sn = data.getString("order_sn");
                    msg.arg1 = 3;
                    handlerData.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handlerData.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handlerData.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handlerData.sendMessage(msg);
                }
            }
        });
    }
    private void getPayContent() {
        String token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/addons/epay/api/submit";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("order_sn", order_sn);
        paramsMap.put("token", token);
        MyLog.e("获取支付信息", token + "=token   order_sn="+order_sn);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handlerData.sendMessage(msg);
                        return;
                    }
                    paydata = jsonObject.getJSONObject("data");
                    msg.arg1 = 4;
                    handlerData.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handlerData.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handlerData.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handlerData.sendMessage(msg);
                }
            }
        });
    }

    public Handler handlerData = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);
                    break;
                case 1:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    ToastUtils.show(R.string.net_error);
                    break;
                case 2:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    tv_price.setText(price);


                    break;
                case 3:
                    getPayContent();
                    break;
                case 4:
                    gopay(paydata.toString());


                    break;
                case 5:

                    break;
                case 6:

                    break;
                case 7:

                    break;
                case 8:


                    break;
                case 9:

                    break;
                case 10:

                    break;
                case 11:
                    sharedPreferences.edit().putString("user_id","").commit();
                    sharedPreferences.edit().putString("username","").commit();
                    sharedPreferences.edit().putString("nickname","").commit();
                    sharedPreferences.edit().putString("mobile","").commit();
                    sharedPreferences.edit().putString("avatar","").commit();
                    sharedPreferences.edit().putString("score","").commit();
                    sharedPreferences.edit().putString("student_id","").commit();
                    sharedPreferences.edit().putString("is_bind_wx","").commit();
                    sharedPreferences.edit().putString("token","").commit();
                    sharedPreferences.edit().putString("is_agent","").commit();
                    sharedPreferences.edit().putString("vip_expire","").commit();
                    sharedPreferences.edit().putString("is_vip","").commit();
                    break;
                case 13:

                    break;

            }

        }
    };

    public void gopay(String content){
//        {"appid":"wx51d9f7800e331c72","partnerid":"1231688202","prepayid":"wx12164426508371820365563b1906338400","timestamp":"1591951439","noncestr":"ORjyLSdWBZ1Dpufn","package":"Sign=WXPay","sign":"312A4E3B96545CB4D55C16D49B600BCF"}
        try {
            JSONObject obj = new JSONObject(content);
            String appid = obj.getString("appid");
            String partnerid = obj.getString("partnerid");
            String prepayid = obj.getString("prepayid");
            String timestamp = obj.getString("timestamp");
            String noncestr = obj.getString("noncestr");
            String packagewx = obj.getString("package");
            String sign = obj.getString("sign");

            PayReq req = new PayReq();

            req.appId = appid;
            req.partnerId = partnerid;
            req.prepayId = prepayid;
            req.nonceStr = noncestr;
            req.timeStamp = timestamp;
            req.packageValue = packagewx;
            req.sign = sign;
            //req.extData = "app data"; // optional
            ToastUtils.show("支付中");
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信

            api = WXAPIFactory.createWXAPI(context, req.appId);
            api.registerApp(req.appId);
            api.sendReq(req);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String paymessage = event.getMessage();
        //0失败   1成功

        String sr = "";
        if ("微信支付成功".equals(paymessage)) {
//            ToastUtils.show("微信支付成功");
            MyLog.e("微信支付成功速读","微信支付成功速读开启速读");
            Intent intent = new Intent(context, FreeSpeedActivity.class);
            intent.putExtra("id",id+"");
            startActivity(intent);
            finish();
        }else if ("微信支付失败".equals(paymessage)) {
//            ToastUtils.show("微信支付失败");

        }else if ("用户取消支付".equals(paymessage)) {
//            ToastUtils.show("用户取消支付");

        }else if ("设备ID已更新退出登录".equals(paymessage)){
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type,context,BuyBookActivity.this,tv_buy);
//            popbyexit(type);
        }


    }


}
